package com.gome.axwl.aoc.web.controller.order;

import com.alibaba.fastjson.JSONObject;
import com.anxl.sso.client.api.AccountInfo;
import com.anxl.sso.client.api.Dc;
import com.anxl.sso.client.api.Token;
import com.anxl.sso.client.support.AnxlSsoSupport;
import com.gome.axwl.aoc.common.constants.LoginConstant;
import com.gome.axwl.aoc.entity.dto.OrderSearchDto;
import com.gome.axwl.aoc.entity.dto.WaybillSearchDto;
import com.gome.axwl.aoc.facade.OrderFacade;
import com.gome.axwl.aoc.facade.TruckFacade;
import com.gome.axwl.aoc.service.sso.ServerGomeSsoClientService;
import com.gome.commons.core.ErrorCode;
import com.gome.commons.core.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 项目名称：gome-axwl-op-system-web
 * 类名称：ResourceController
 * 类描述：
 * 创建人：chengh
 * 创建时间：2018年4月24日16:59:06
 */
@Api(tags = "订单查询")
@RestController
public class OrderController {

    private final static Logger log = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    OrderFacade orderFacade;

    @Autowired
    TruckFacade truckFacade;

    @Autowired
    private ServerGomeSsoClientService ssoClientService;

    @ApiOperation(value = "模糊查询服务商列表", notes = "development by chengh")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "查询关键字", paramType = "query", dataType = "String", required = true)
    })
    @RequestMapping(value = "carrier/queryCarrier", method = RequestMethod.POST)
    public Object getCarrierByKeyword(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse response) {
        AccountInfo accountInfo = (AccountInfo) request.getSession().getAttribute(LoginConstant.LOGIN_USER);
        if (accountInfo == null) {
            Token token = (Token) request.getSession().getAttribute(AnxlSsoSupport.SSO_CONTEXT);
            accountInfo = ssoClientService.getUserByLocalUserId(token.getUid(), request, response);
        }
        List<Dc> dcList = accountInfo.getDcs();         //dc集合
        StringBuffer dcId = new StringBuffer();
        String dcIdString;
        if (dcList != null && dcList.size() > 0) {
            for (int i = 0; i < dcList.size(); i++) {
                dcId.append(",").append(dcList.get(i).getDcId());
            }

            if (dcId.length() > 0) {
                dcIdString = dcId.toString().substring(1, dcId.length());
            } else {
                dcIdString = "0";
            }
        } else {
            dcIdString = "0";
        }
        log.info("调用TruckController.getCarrierByKeyword(模糊查询服务商列表),dcid列表{},参数为:{}", dcIdString, map.toString());
        return orderFacade.getCarrierByKeyword(map.get("keyword"), dcIdString);
    }

    @ApiOperation(value = "查询订单列表", notes = "development by chengh")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "customerAccount", value = "客户账号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "carrierId", value = "服务商", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "status", value = "订单状态", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "pickStartTime", value = "计划取货时间开始", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "pickEndTime", value = "计划取货时间结束", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "deliverStartTime", value = "计划送达开始时间", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "deliverEndTime", value = "计划送达结束时间", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "taskNo", value = "任务单号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "waybillNo", value = "运单号/lmis运单号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "orderType", value = "订单类型", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "serviceProviderId", value = "服务商id", paramType = "query", dataType = "String", required = true)
    })
    @RequestMapping(value = "order/getOrderList", method = RequestMethod.POST)
    public ResultData getOrderList(@RequestBody OrderSearchDto orderSearchDto, HttpServletRequest request, HttpServletResponse response) {
        log.info("调用OrderController.getOrderList(查询订单列表),参数为:" + orderSearchDto.toString());
        AccountInfo accountInfo = (AccountInfo) request.getSession().getAttribute(LoginConstant.LOGIN_USER);
        if (accountInfo == null) {
            Token token = (Token) request.getSession().getAttribute(AnxlSsoSupport.SSO_CONTEXT);
            accountInfo = ssoClientService.getUserByLocalUserId(token.getUid(), request, response);
        }
        List<Dc> dcList = accountInfo.getDcs();         //dc集合
        if (dcList != null && dcList.size() > 0) {      //用户有dc
            Integer[] acceptDcIds = new Integer[dcList.size()];
            for (int i = 0; i < dcList.size(); i++) {
                acceptDcIds[i] = dcList.get(i).getDcId();
            }
            orderSearchDto.setAcceptDcIds(acceptDcIds);
        } else {          //用户没有dc
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", null);
            jsonObject.put("pageNum", 1);
            jsonObject.put("pageSize", orderSearchDto.getPageSize());
            jsonObject.put("pages", 0);
            jsonObject.put("size", 0);
            jsonObject.put("total", 0);
            return new ResultData(ErrorCode.SUCCESS, ErrorCode.SUCCESS_MSG, jsonObject);
        }
        log.info("登录用户:{},session中DC权限为:{},查询的DC为:{}", accountInfo.getAccountNo(), dcList.toString(), orderSearchDto.getAcceptDcIds());
        return orderFacade.getOrderList(orderSearchDto);
    }

    @ApiOperation(value = "查询订单详情", notes = "development by chengh")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNo", value = "订单号", paramType = "query", dataType = "String", required = true)
    })
    @RequestMapping(value = "order/getOrderDetail", method = RequestMethod.POST)
    public ResultData getOrderDetail(@RequestBody Map<String, String> map, HttpServletRequest request) {
        log.info("调用OrderController.getOrderDetail(查询订单详情),参数为:" + map.toString());
        return orderFacade.getOrderDetail(map.get("orderNo"));
    }

    @ApiOperation(value = "查询运单列表", notes = "development by chengh")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", paramType = "query", dataType = "int", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", paramType = "query", dataType = "int", required = true)
    })
    @RequestMapping(value = "waybill/getWaybillList", method = RequestMethod.POST)
    public Object getWaybillByOrderNo(@RequestBody WaybillSearchDto waybillSearchDto, HttpServletRequest request) {
        String taskNo = waybillSearchDto.getTaskNo();
        String orderId = waybillSearchDto.getOrderId();
        if ((StringUtils.isEmpty(taskNo) || "null".equals(taskNo)) && (StringUtils.isEmpty(orderId) || "null".equals(orderId))) {
            return ResultData.newResultData(ErrorCode.FAILOR, "taskNo or orderId不能同时为空!");
        }
        log.info("调用OrderController.getWaybillByOrderNo(查询运单列表),参数为:" + waybillSearchDto.toString());
        return orderFacade.getWaybillByOrderNo(waybillSearchDto);
    }

    @ApiOperation(value = "查询运单详情", notes = "development by chengh")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "waybillNo", value = "运单号", paramType = "query", dataType = "String", required = true)
    })
    @RequestMapping(value = "waybill/getWaybillDetail", method = RequestMethod.POST)
    public ResultData getWaybillDetail(@RequestBody Map<String, String> map, HttpServletRequest request) {
        log.info("调用OrderController.getWaybillDetail(查询运单详情),参数为:" + map.toString());
        return orderFacade.getWaybillDetail(map.get("waybillNo"));
    }

    @ApiOperation(value = "拒签照片下载", notes = "development by John Li")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "waybillNo", value = "运单号", paramType = "query", dataType = "String", required = true)
    })
    @RequestMapping(value = "waybill/downloadRefuseFile", method = RequestMethod.GET)
    public ResultData downloadRefuseFile(@RequestParam String waybillNo, HttpServletResponse response) {
        log.info("调用OrderController.downloadRefuseFile(查询运单详情),参数为:" + waybillNo.toString());
        JSONObject json = orderFacade.downloadRefuseFile(waybillNo, response);
        return truckFacade.downloadFileByUrl(json.getString("fileName"), Arrays.asList(json.getString("urlStr").split(",")), response);
    }

    @ApiOperation(value = "查询状态字典", notes = "development by chengh")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "状态类型", paramType = "query", dataType = "String", required = true)
    })
    @RequestMapping(value = "status/getStatus", method = RequestMethod.POST)
    public ResultData getStatus(@RequestBody Map<String, String> map, HttpServletRequest request) {
        log.info("调用OrderController.getStatus(查询状态字典),参数为:" + map.toString());
        return orderFacade.getStatus(map.get("code"));
    }

}
